﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Reflection;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Reflection;
using System.ComponentModel;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Colors;
using System.Drawing;
using System.Drawing.Imaging;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Reflection;
using System.ComponentModel;


namespace cadbom
{
    public partial class SetBomMaterialForm : Form
    {
        QueryMaterialProductForm queryForm = null;
        QueryMaterialForm form = null;
        NetApi netApi = new NetApi();
        List<BasMaterial> addMaterialList = new List<BasMaterial>();
        Dictionary<String, ProductBomTree> dictionary = new Dictionary<String, ProductBomTree>();
        BasProduct queryProduct;
        String mainProductCode = "";
        String sizeLength = "";
        String sizeWidth = "";
        ProductBomTree checkedProductBomTree = null;
        MaterialPropertyForm propertyForm = null;
        private string baigeBlockCadHandleId;

        private System.Data.DataTable dtBand = null;

        public SetBomMaterialForm()
        {
            InitializeComponent();
            initGridView();
            this.textBox1.ReadOnly = true; 
        }

        public void initBomFormData()
        {
            if (GValues.productCode != "")
            {
                this.textBox1.Text = GValues.productCode;
                this.button2_Click(null, null);
                this.button9.Text = GValues.clickButtonText;
            }
            else
            {
                this.button9.Text = GValues.clickButtonText;
            }

        }
        private void initGridView(){
            if (dtBand == null)
            {
                dtBand = new System.Data.DataTable();
                dtBand.Columns.Add("code");
                dtBand.Columns.Add("name");
                dtBand.Columns.Add("drawingNo");
                dtBand.Columns.Add("description");
                dtBand.Columns.Add("qty");
                dtBand.Columns.Add("version");
                dtBand.Columns.Add("unitId_dictText");
                dtBand.Columns.Add("typeName");
                dtBand.Columns.Add("id");
                dtBand.Columns.Add("pid");
                dtBand.Columns.Add("uuid");
                dtBand.Columns.Add("handleId");
                dtBand.Columns.Add("nodeType");
                dtBand.Columns.Add("nodeType_dictText");
            }
            this.dataGridView1.DataSource = dtBand;
            dataGridView1.Columns["code"].HeaderText = "物料编码";
            dataGridView1.Columns["name"].HeaderText = "物料名称";
            dataGridView1.Columns["drawingNo"].HeaderText = "物料规格";
            dataGridView1.Columns["description"].HeaderText = "物料描述";
            dataGridView1.Columns["qty"].HeaderText = "用量";
            dataGridView1.Columns["version"].HeaderText = "版本";

            dataGridView1.Columns["unitId_dictText"].HeaderText = "单位";
            dataGridView1.Columns["typeName"].HeaderText = "物料类别";
            dataGridView1.Columns["nodeType_dictText"].HeaderText = "类型";
            this.dataGridView1.Columns["id"].Visible = false;
            this.dataGridView1.Columns["pid"].Visible = false;
            this.dataGridView1.Columns["uuid"].Visible = false;
            this.dataGridView1.Columns["handleId"].Visible = false;
            this.dataGridView1.Columns["nodeType"].Visible = false;

            dataGridView1.Columns["code"].ReadOnly = true;
            dataGridView1.Columns["name"].ReadOnly = true;
            dataGridView1.Columns["drawingNo"].ReadOnly = true;
            dataGridView1.Columns["description"].ReadOnly = true;
            dataGridView1.Columns["version"].ReadOnly = true;
            dataGridView1.Columns["unitId_dictText"].ReadOnly = true;
            dataGridView1.Columns["typeName"].ReadOnly = true;
            dataGridView1.Columns["nodeType_dictText"].ReadOnly = true;
            foreach (DataGridViewColumn item in dataGridView1.Columns) item.SortMode = DataGridViewColumnSortMode.NotSortable;
        }

        //产品数据查询
        private void button2_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text) && netApi != null)
            {
                this.mainProductCode = "";
                this.queryProduct = null;
                netApi.getProductData(textBox1.Text.Trim(), new Action<BasProduct>((product) =>
                {
                    if (product == null)
                    {
                        MessageBox.Show("Product data not found or returned null");
                        return;
                    }
                    this.queryProduct = product;
                    this.mainProductCode = product.code;
                    this.textBox2.Text = product.custId_dictText;
                    this.textBox7.Text = product.productType_dictText;
                    this.textBox16.Text = product.code;
                    this.textBox3.Text = product.custCode;
                    this.textBox8.Text = product.drawingNo;
                    this.textBox15.Text = product.stage_dictText;
                    this.textBox4.Text = product.name;
                    this.textBox9.Text = product.productVer == null ? "" : product.productVer;
                    this.textBox14.Text = product.unitId_dictText;
                    this.textBox11.Text = product.sizeLength;
                    this.textBox12.Text = product.sizeWidth;
                    this.textBox6.Text = product.productBomHandleId;
                    //initDataGridView(product.id);
                    if (product.id != null)
                    {
                        initDataGridView(product.id);
                    }
                    else
                    {
                        MessageBox.Show("Product ID is null");
                    }
                }));
            }
        }

        //添加物料数据
        private void button5_Click(object sender, EventArgs e)
        {
            if (this.queryProduct == null)
            {
                return;
            }
            if (form != null)
            {
                form.Dispose();
                form = null;
            }
            form = new QueryMaterialForm(new Action<BasMaterial>((item) => {
                bool addFlag = false;
                if (dtBand != null && dtBand.Rows.Count > 0)
                {
                    
                    int adults = dtBand.AsEnumerable().Where(row => row["id"].ToString() == item.id).Count();
                    if (adults > 0)
                    {
                        MessageBox.Show("物料已经添加了！");
                        addFlag = false;
                    }
                    else
                    {
                        addFlag = true;
                    }

                }
                else
                {
                    addFlag = true;
                }
                if (addFlag)
                {
                    //addMaterialList.Add(item);
                    String uuid = Guid.NewGuid().ToString();
                    ProductBomTree bomTree = new ProductBomTree();
                    bomTree.code = item.code;
                    bomTree.name = item.nameDesc;
                    bomTree.drawingNo = item.model;
                    bomTree.description = item.description;
                    List<MrpProductBomMaterialProperty> list = JsonConvert.DeserializeObject<List<MrpProductBomMaterialProperty>>(JsonConvert.SerializeObject(item.basMaterialProperties));
                    bomTree.materialProperties = list;
                    bomTree.version = item.materialVer;
                    bomTree.qty = "0";
                    bomTree.unitId_dictText = item.unitId_dictText;
                    bomTree.typeName = item.typeName;
                    bomTree.id = item.id;
                    bomTree.pid = this.queryProduct.id;
                    bomTree.nodeType = "3";
                    dictionary.Add(uuid, bomTree);
                    DataRow dr = dtBand.NewRow();
                    dr["code"] = item.code;
                    dr["name"] = item.nameDesc;
                    dr["drawingNo"] = item.model;
                    dr["description"] = item.description;
                    dr["qty"] = 0;
                    dr["version"] = item.materialVer;

                    dr["unitId_dictText"] = item.unitId_dictText;
                    dr["typeName"] = item.typeName;
                    dr["id"] = item.id;
                    dr["pid"] = this.queryProduct.id;
                    dr["uuid"] = uuid;
                    dr["handleId"] = "";
                    dr["nodeType"] = "3";
                    dr["nodeType_dictText"] = "物料";
                    dtBand.Rows.Add(dr);
                    this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1;
                }
            }));
            form.Owner = this;
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(this, form);
        }

        //移除BOM物料数据
        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                List<int> selectRows = new List<int>();
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    if (this.dataGridView1.Rows[i].Cells["Column1"].Value != null)
                    {
                        string checkRows = this.dataGridView1.Rows[i].Cells["Column1"].Value.ToString();
                        if (checkRows != null && ((string)checkRows) == "1")
                        {
                            selectRows.Add(i);
                        }
                    }

                }
                List<DataRow> rowsToDelete = new List<DataRow>();
                foreach (DataRow row in dtBand.Rows)
                {
                    int rowindex = row.Table.Rows.IndexOf(row);
                    if (selectRows.Contains(rowindex))
                    {
                        rowsToDelete.Add(row);
                    }
                }
                foreach (DataRow row in rowsToDelete)
                {
                    dtBand.Rows.Remove(row);
                }
            }
            catch (System.Exception err)
            {

            }
        }

        //private void button7_Click(object sender, EventArgs e)
        //{
        //    QueryMaterialForm form = new QueryMaterialForm();
        //    form.Owner = this;
        //    Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(this, form);
        //}

        public List<T> ConvertDataTableToList<T>(System.Data.DataTable dataTable) where T : new()
        {
            List<T> list = new List<T>();

            foreach (DataRow row in dataTable.Rows)
            {
                T obj = new T();

                foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
                {
                    if (dataTable.Columns.Contains(propertyInfo.Name))
                    {
                        if (row[propertyInfo.Name] != DBNull.Value)
                        {
                            propertyInfo.SetValue(obj, row[propertyInfo.Name], null);
                        }
                    }
                }

                list.Add(obj);
            }

            return list;
        }
        private void saveBomFormData()
        {
            String tag = "saveBomFormData";
            MrpProductBomVo mrpProductBomVo = new MrpProductBomVo();
            mrpProductBomVo.productBomHandleId = GValues.cadHandleId;
            mrpProductBomVo.sizeLength = this.sizeLength; //长度
            mrpProductBomVo.sizeWidth = this.sizeWidth; //宽度
            mrpProductBomVo.pid = this.queryProduct.id;
            List<ProductBomTree> bomTrees = ConvertDataTableToList<ProductBomTree>(dtBand);
            List<MrpProductBom> mrpProductBoms = new List<MrpProductBom>();
            int i = 0;
            foreach (ProductBomTree item in bomTrees)
            {
                i++;
                MrpProductBom mrpProductBom = new MrpProductBom();
                mrpProductBom.nodeId = item.id;
                mrpProductBom.pid = item.pid;
                mrpProductBom.qty = item.qty;
                mrpProductBom.hasChild = item.nodeType == "2" ? "true" : "false";
                mrpProductBom.productionMethod = item.nodeType == "2" ? "1" :"2";
                mrpProductBom.nodeType = item.nodeType;
                mrpProductBom.unitId = item.unitId;
                mrpProductBom.handleId = item.handleId;
                mrpProductBoms.Add(mrpProductBom);
                mrpProductBom.sort = i.ToString();
            }
            mrpProductBomVo.mrpProductBoms = mrpProductBoms;
            netApi.saveProductBom(mrpProductBomVo, new Action<string>(res =>
            {
                if (res == "ok") //访问成功
                {
                    MessageBox.Show("保存产品BOM物料数据成功！");
                    LogHelper.WriteLog(tag + "保存产品BOM物料数据成功！");
                }
                else
                {
                    LogHelper.WriteLog(tag + "保存产品BOM物料数据失败！");

                }
            }));
        }
        //保存BOM物料数据
        private void button9_Click(object sender, EventArgs e)
        {
            GValues.productCode = this.queryProduct.code;
            GValues.productCustCode = this.queryProduct.custCode;
            String result = "";
            if (this.button9.Text == "插入")
            {
                if (this.dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("表格中没数据可以插入到CAD表格！");
                }
                else
                {
                    List<string[]> insertTableDatas = new List<string[]>();
                    foreach (DataGridViewRow item in this.dataGridView1.Rows)
                    {
                        insertTableDatas.Add(new string[] {
                        item.Cells["typeName"].FormattedValue.ToString(), //类型
                        item.Cells["name"].FormattedValue.ToString(), //名称
                        item.Cells["drawingNo"].FormattedValue.ToString(), //规格
                        item.Cells["qty"].FormattedValue.ToString(),
                    });
                    }
                    this.sizeLength = this.textBox11.Text;
                    this.sizeWidth = this.textBox12.Text;
                    this.Close(); //操作cad之前关闭窗口
                    SetObject setObject = new SetObject();
                    setObject.InsertTableSelection(insertTableDatas);
                    
                    this.saveBomFormData();
                }
            }
            if (this.button9.Text == "修改")
            {
                if (this.dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("表格中没数据可以编辑到CAD表格！");
                }
                else
                {
                    GValues.cadHandleId = queryProduct.productBomHandleId;
                    List<string[]> insertTableDatas = new List<string[]>();
                    foreach (DataGridViewRow item in this.dataGridView1.Rows)
                    {
                        insertTableDatas.Add(new string[] {
                        item.Cells["typeName"].FormattedValue.ToString(), //类型
                        item.Cells["name"].FormattedValue.ToString(), //名称
                        item.Cells["drawingNo"].FormattedValue.ToString(), //规格
                        item.Cells["qty"].FormattedValue.ToString(),
                        });
                    }
                    this.sizeLength = this.textBox11.Text;
                    this.sizeWidth = this.textBox12.Text;
                    SetObject setObject = new SetObject();
                    setObject.UpdateTableSelection(insertTableDatas);
                    this.Close(); //操作cad之前关闭窗口
                    this.saveBomFormData();
                }
            }
        }
        private void initDataGridView(String productId)
        {
            dtBand.Clear();
            dictionary = new Dictionary<String,ProductBomTree>();
            netApi.getProductBom(productId, new Action<List<ProductBomTree>>((items) =>
            {
               items =  items.OrderBy(p => int.Parse(p.sort !=null ? p.sort: "0")).ToList();
                foreach (ProductBomTree mpb in items)
                {
                    if (mpb.name == null || mpb.name == "")
                    {
                        if (mpb.realName != null && mpb.realName != "")
                        {
                            mpb.name = mpb.realName;
                        }
                    }   
                    mpb.pid = productId;
                    String uuid = Guid.NewGuid().ToString();

                    double bomQty = double.Parse(mpb.qty);
                    double _sizeLength = 0;
                    double _sizeWidth = 0;
                    double _materialSizeLength = 0;
                    double _materialSizeWidth = 0;
                    if (this.textBox11.Text != null && this.textBox11.Text != "")
                    {
                        _sizeLength = double.Parse( this.textBox11.Text);
                    }
                    if (this.textBox12.Text != null && this.textBox12.Text != "")
                    {
                        _sizeWidth = double.Parse(this.textBox12.Text);
                    }
                    if (mpb.sizeLength != null && mpb.sizeLength != "" ) {
                        _materialSizeLength = double.Parse(mpb.sizeLength);
                    }
                    if (mpb.sizeWidth != null && mpb.sizeWidth != "") {
                        _materialSizeWidth = double.Parse(mpb.sizeWidth);
                    }
                    if (_sizeWidth > 0 && _sizeLength > 0 && _materialSizeWidth>0 && _materialSizeLength>0)
                    {
                        bomQty = (_sizeLength * _sizeWidth) / (_materialSizeLength * _materialSizeWidth);
                        bomQty = Math.Round(bomQty * (1 + GValues.BlockField_LossRate), 4);
                    }
                    mpb.qty = bomQty.ToString();

                    dictionary.Add(uuid, mpb);
                    DataRow dr = dtBand.NewRow();
                    dr["code"] = mpb.code;
                    dr["name"] = mpb.name;
                    dr["drawingNo"] = mpb.drawingNo;
                    dr["description"] = mpb.description;
                    dr["qty"] = mpb.qty;
                    dr["version"] = mpb.version;

                    dr["unitId_dictText"] = mpb.unitId_dictText;
                    dr["typeName"] = mpb.typeName;
                    dr["id"] = mpb.id;
                    dr["pid"] = mpb.pid;
                    dr["uuid"] = uuid;
                    dr["handleId"] = mpb.handleId;
                    dr["nodeType"] = mpb.nodeType;
                    dr["nodeType_dictText"] = mpb.nodeType == "2" ? "产品" : "物料";
                    dtBand.Rows.Add(dr);
                }
            }));
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
                        using
            (SolidBrush b =
            new
            SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
                        {

                            string
                            linenum = e.RowIndex.ToString();
                            int
                            linen = 0;
                            linen = Convert.ToInt32(linenum) + 1;
                            string
                            line = linen.ToString();
                            e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 5);
                            SolidBrush B =
                            new
                            SolidBrush(System.Drawing.Color.Red);
                        }
        }

        private void SetBomMaterialForm_Load(object sender, EventArgs e)
        {

        }

        private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            // 假设我们要改变特定列（例如列名为"Status"）的值为"High"的行的颜色
            if (dataGridView1.Rows[e.RowIndex].Cells["Status"].Value != null && dataGridView1.Rows[e.RowIndex].Cells["Status"].Value.ToString() == "High")
            {
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = System.Drawing.Color.Red; // 设置为红色
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.SelectionBackColor = System.Drawing.Color.Red; // 设置选中时的背景色
            }
        }
        private void addDrawingMaterialProperty()
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                if (propertyForm != null)
                {
                    propertyForm.Close();
                    //propertyForm.Dispose();
                    propertyForm = null;
                }
                if (this.dataGridView1.Rows[i].Cells["Column1"].Value != null)
                {
                    string checkRows = this.dataGridView1.Rows[i].Cells["Column1"].Value.ToString();
                    if (checkRows != null && ((string)checkRows) == "1")
                    {
                        //selectRows.Add(i);
                        checkedProductBomTree = dictionary[this.dataGridView1.Rows[i].Cells["uuid"].Value.ToString()];
                        if (checkedProductBomTree.materialProperties != null && checkedProductBomTree.materialProperties.Count() > 0)
                        {
                            //propertyForm.initGridviewData(checkedProductBomTree.materialProperties);
                            SetObject setObject = new SetObject();
                            List<String> handleIdList = (this.dataGridView1.Rows[i].Cells["handleId"].Value.ToString()).Split(',').ToList();
                            int qty = int.Parse(this.dataGridView1.Rows[i].Cells["qty"].Value.ToString());
                            setObject.addSelectAndLabel(checkedProductBomTree, handleIdList, qty, new Action<int, List<String>>((count, handleIds) =>
                            {
                                checkedProductBomTree.qty = count.ToString();
                                DataRow data = dtBand.AsEnumerable().Where(row => row["id"].ToString() == checkedProductBomTree.id.ToString()).FirstOrDefault();
                                data["qty"] = count;
                                data["handleId"] = String.Join(",", handleIds);
                                dataGridView1.Refresh();
                            }));

                        }
                        else
                        {
                            MessageBox.Show("特征信息没设定！");
                        }
                    }
                }
            }
        }
        private void cancelDrawingMaterialProperty()
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                if (propertyForm != null)
                {
                    propertyForm.Close();
                    //propertyForm.Dispose();
                    propertyForm = null;
                }
                if (this.dataGridView1.Rows[i].Cells["Column1"].Value != null)
                {
                    string checkRows = this.dataGridView1.Rows[i].Cells["Column1"].Value.ToString();
                    if (checkRows != null && ((string)checkRows) == "1")
                    {
                        //selectRows.Add(i);
                        checkedProductBomTree = dictionary[this.dataGridView1.Rows[i].Cells["uuid"].Value.ToString()];
                        if (checkedProductBomTree.materialProperties != null && checkedProductBomTree.materialProperties.Count() > 0)
                        {
                            //propertyForm.initGridviewData(checkedProductBomTree.materialProperties);
                            SetObject setObject = new SetObject();
                            List<String> handleIdList = (this.dataGridView1.Rows[i].Cells["handleId"].Value.ToString()).Split(',').ToList();
                            int qty = int.Parse(this.dataGridView1.Rows[i].Cells["qty"].Value.ToString());
                            setObject.cancelSelectAndLabel(checkedProductBomTree, handleIdList,qty, new Action<int, List<String>>((count, handleIds) =>
                            {
                                checkedProductBomTree.qty = count.ToString();
                                DataRow data = dtBand.AsEnumerable().Where(row => row["id"].ToString() == checkedProductBomTree.id.ToString()).FirstOrDefault();
                                data["qty"] = count;
                                data["handleId"] = String.Join(",", handleIds);
                                dataGridView1.Refresh();
                            }));

                        }
                        else
                        {
                            MessageBox.Show("特征信息没设定！");
                        }
                    }
                }
            }
        }
        private void drawingMaterialProperty()
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                if (propertyForm != null)
                {
                    propertyForm.Close();
                    //propertyForm.Dispose();
                    propertyForm = null;
                }
                if (this.dataGridView1.Rows[i].Cells["Column1"].Value != null)
                {
                    string checkRows = this.dataGridView1.Rows[i].Cells["Column1"].Value.ToString();
                    if (checkRows != null && ((string)checkRows) == "1" && (this.dataGridView1.Rows[i].Cells["handleId"].Value ==null || this.dataGridView1.Rows[i].Cells["handleId"].Value == ""))
                    {
                        //selectRows.Add(i);
                        checkedProductBomTree = dictionary[this.dataGridView1.Rows[i].Cells["uuid"].Value.ToString()];
                        if (checkedProductBomTree.materialProperties != null && checkedProductBomTree.materialProperties.Count() > 0)
                        {
                            //propertyForm.initGridviewData(checkedProductBomTree.materialProperties);
                            SetObject setObject = new SetObject();
                            setObject.SelectAndLabel(checkedProductBomTree.materialProperties, new Action<int,List<String>>((count,handleIds)=>{
                                checkedProductBomTree.qty = count.ToString();
                                DataRow data = dtBand.AsEnumerable().Where(row => row["id"].ToString() == checkedProductBomTree.id.ToString()).FirstOrDefault();
                                data["qty"] = count;
                                data["handleId"] = String.Join(",",handleIds);
                                dataGridView1.Refresh();
                            }));

                        }
                        else
                        {
                            MessageBox.Show("特征信息没设定！");
                        }
                    }
                }
            }
        }
        private void setCheckedData()
        {
            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                //if (propertyForm != null)
                //{
                //    propertyForm.Close();
                //    //propertyForm.Dispose();
                //    propertyForm = null;
                //}
                if (this.dataGridView1.Rows[i].Cells["Column1"].Value != null)
                {
                    string checkRows = this.dataGridView1.Rows[i].Cells["Column1"].Value.ToString();
                    if (checkRows != null && ((string)checkRows) == "1")
                    {
                        //selectRows.Add(i);
                        checkedProductBomTree = dictionary[this.dataGridView1.Rows[i].Cells["uuid"].Value.ToString()];
                        if (checkedProductBomTree.materialProperties != null && checkedProductBomTree.materialProperties.Count() > 0)
                        {
                            if (propertyForm != null)
                            {
                                propertyForm.Close();
                                //propertyForm.Dispose();
                                propertyForm = null;
                            }
                            propertyForm = new MaterialPropertyForm(new Action<int,List<String>>((count,handleIds) => {
                                checkedProductBomTree.qty = count.ToString();
                                DataRow data  = dtBand.AsEnumerable().Where(row => row["id"].ToString() == checkedProductBomTree.id.ToString()).FirstOrDefault();
                                data["qty"] = count;
                                data["handleId"] = String.Join(",", handleIds);
                                dataGridView1.Refresh();
                            }));
                            propertyForm.initGridviewData(checkedProductBomTree.materialProperties);
                            propertyForm.Owner = this;
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(this, propertyForm);
                        }
                        else
                        {
                            MessageBox.Show("特征信息没设定！");
                        }
                    }
                }
            }
        }

        //鼠标点击内容部分
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0) // 确保是复选框列被点击
            {
                // 取消所有其他行的复选框选中状态
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Index != e.RowIndex) // 排除当前行
                    {
                        row.Cells[0].Value = 0; // 取消选中状态
                    }
                }
            }
        }

        //选择CAD对象属性并画圆
        private void button1_Click(object sender, EventArgs e)
        {
            drawingMaterialProperty();
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            //setCheckedData();
        }

        //获取物料特征信息
        private void button3_Click(object sender, EventArgs e)
        {
            setCheckedData();
        }

        //cells数据变化事件
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (propertyForm != null)
            {
                propertyForm.Dispose();
                propertyForm = null;
            }
            if (e.RowIndex >= 0 && e.ColumnIndex == dataGridView1.Columns["Column1"].Index)
            {
                // 获取更改的单元格值
                var isChecked = dataGridView1.Rows[e.RowIndex].Cells["Column1"].Value;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Index == e.RowIndex) // 排除当前行
                    {
                        if (isChecked.ToString() == "1")
                        {
                            //button1.Visible = true;  //
                            //button3.Visible = true; //特征信息
                            //button4.Visible = true; //取消
                            //button7.Visible = true; //添加
                            //MessageBox.Show("checked" + e.RowIndex);
                            //setCheckedData();
                        }
                        else
                        {
                            //MessageBox.Show("no checked" + e.RowIndex);
                        }
                    }
                }


            }
        }
        private void dataGridView1_CellValueChangedA(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView grid = sender as DataGridView;
            if (grid != null && e.RowIndex >= 0)
            {
                if (grid.Columns[e.ColumnIndex].Name == "Column1")
                {
                    System.Data.DataTable dt = grid.DataSource as System.Data.DataTable;
                    DataGridViewCheckBoxCell checkbox = grid.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell; // 获得checkbox列单元格
                    if (checkbox != null && checkbox.Value.ToString() == "1")
                    {
                        MessageBox.Show("checked : " + e.RowIndex);
                    }
                    else
                    {
                        MessageBox.Show("no checked : " + e.RowIndex);
                    }
                }
            }
        }

        private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            //提交改变，触发dataGridView1_CellValueChanged事件，以便及时获取check的值改变事件
            if (dataGridView1.IsCurrentCellDirty)
                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
        //取消对象
        private void button4_Click(object sender, EventArgs e)
        {
            cancelDrawingMaterialProperty();
        }
        //添加对象
        private void button7_Click(object sender, EventArgs e)
        {
            addDrawingMaterialProperty();
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {

        }
        private void getBomItem()
        {
            if (this.queryProduct == null)
            {
                return;
            }
            if (queryForm != null)
            {
                queryForm.Dispose();
                queryForm = null;
            }
            queryForm = new QueryMaterialProductForm(new Action<BasProduct>((item) =>
            {
                bool addFlag = false;
                if (dtBand != null && dtBand.Rows.Count > 0)
                {
                    int adults = dtBand.AsEnumerable().Where(row => row["id"].ToString() == item.id).Count();
                    if (adults > 0)
                    {
                        this.Invoke(new Action(() =>
                        {
                            MessageBox.Show("产品已经添加了！");
                        }));
                        addFlag = false;
                    }
                    else if (item.code == this.mainProductCode)
                    {
                        this.Invoke(new Action(() =>
                        {
                            MessageBox.Show("产品不可以添加自己！");
                        }));
                        addFlag = false;
                    }
                    else
                    {
                        addFlag = true;
                    }

                }
                else
                {
                    addFlag = true;
                }
                if (addFlag)
                {
                    //addMaterialList.Add(item);
                    String uuid = Guid.NewGuid().ToString();
                    ProductBomTree bomTree = new ProductBomTree();
                    bomTree.code = item.code;
                    bomTree.name = item.name;
                    bomTree.drawingNo = item.drawingNo;
                    bomTree.description = item.description;
                    //List<MrpProductBomMaterialProperty> list = JsonConvert.DeserializeObject<List<MrpProductBomMaterialProperty>>(JsonConvert.SerializeObject(item.basMaterialProperties));
                    //bomTree.materialProperties = list;
                    bomTree.version = item.productVer;
                    bomTree.qty = "0";
                    bomTree.unitId_dictText = item.unitId_dictText;
                    bomTree.typeName = item.custCode;
                    bomTree.id = item.id;
                    bomTree.pid = this.queryProduct.id;
                    bomTree.nodeType = "2";
                    dictionary.Add(uuid, bomTree);
                    DataRow dr = dtBand.NewRow();
                    dr["code"] = item.code;
                    dr["name"] = item.name;
                    dr["drawingNo"] = item.drawingNo == null || item.drawingNo == "" ? item.custCode : item.drawingNo;
                    dr["description"] = item.description;
                    dr["qty"] = 1;
                    dr["version"] = item.productVer;

                    dr["unitId_dictText"] = item.unitId_dictText;
                    dr["typeName"] = "半成品"; // item.custCode;
                    dr["id"] = item.id;
                    dr["pid"] = this.queryProduct.id;
                    dr["uuid"] = uuid;
                    dr["handleId"] = "";
                    dr["nodeType"] = "2";
                    dr["nodeType_dictText"] = "产品";
                    dtBand.Rows.Add(dr);
                    this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1;
                }

            }), new Action<BasMaterial>((item) =>
            {
                bool addFlag = false;
                if (dtBand != null && dtBand.Rows.Count > 0)
                {

                    int adults = dtBand.AsEnumerable().Where(row => row["id"].ToString() == item.id).Count();
                    if (adults > 0)
                    {
                        this.Invoke(new Action(() =>
                        {
                            MessageBox.Show("物料已经添加了！");
                        }));
                        addFlag = false;
                    }
                    else
                    {
                        addFlag = true;
                    }

                }
                else
                {
                    addFlag = true;
                }
                if (addFlag)
                {

                    double _sizeLength = 0.0;
                    double _sizeWidth = 0.0;
                    double _materialSizeLength = 0.0;
                    double _materialSizeWidth = 0.0;
                    try
                    {
                        if (this.textBox11.Text != null && this.textBox11.Text != "")
                        {
                            _sizeLength = double.Parse(this.textBox11.Text);
                        }
                        if (this.textBox12.Text != null && this.textBox12.Text != "")
                        {
                            _sizeWidth = double.Parse(this.textBox12.Text);
                        }
                        if (item.sizeLength != null && item.sizeLength != "")
                        {
                            _materialSizeLength = double.Parse(item.sizeLength);
                        }
                        if (item.sizeWidth != null && item.sizeWidth != "")
                        {
                            _materialSizeWidth = double.Parse(item.sizeWidth);
                        }
                    }
                    catch (System.Exception ex)
                    {

                    }
                    double bomQty = 1;
                    if (_materialSizeWidth > 0 && _materialSizeLength > 0)
                    {
                        bomQty = (_sizeLength * _sizeWidth) / (_materialSizeLength * _materialSizeWidth);
                        bomQty = Math.Round(bomQty * (1 + GValues.BlockField_LossRate), 4);
                    }
                    if (item.typeName == "粉末" && item.area != null && item.area != "")
                    {
                        double area = double.Parse(item.area);
                        if (area > 0)
                        {
                            bomQty = ((_sizeLength * _sizeWidth) * 0.000001 * 2 * (1 + GValues.BlockField_FenmoLossRate)) / area;
                            bomQty = Math.Round(bomQty, 4);
                        }
                    }
                    //addMaterialList.Add(item);
                    String uuid = Guid.NewGuid().ToString();
                    ProductBomTree bomTree = new ProductBomTree();
                    bomTree.code = item.code;
                    bomTree.name = item.nameDesc;
                    bomTree.drawingNo = item.model;
                    bomTree.description = item.description;
                    List<MrpProductBomMaterialProperty> list = JsonConvert.DeserializeObject<List<MrpProductBomMaterialProperty>>(JsonConvert.SerializeObject(item.basMaterialProperties));
                    bomTree.materialProperties = list;
                    bomTree.version = item.materialVer;
                    bomTree.qty = "0";
                    bomTree.unitId_dictText = item.unitId_dictText;
                    bomTree.typeName = item.typeName;
                    bomTree.id = item.id;
                    bomTree.pid = this.queryProduct.id;
                    bomTree.nodeType = "3";
                    dictionary.Add(uuid, bomTree);
                    DataRow dr = dtBand.NewRow();
                    string matName = "";
                    matName = item.nameDesc;
                    if (matName == null || matName == "")
                    {
                        matName = item.realName;
                    }
                    dr["code"] = item.code;
                    dr["name"] = matName;//item.nameDesc;
                    dr["drawingNo"] = item.model;
                    dr["description"] = item.description;
                    dr["qty"] = bomQty;
                    dr["version"] = item.materialVer;

                    dr["unitId_dictText"] = item.unitId_dictText;
                    dr["typeName"] = item.typeName;
                    dr["id"] = item.id;
                    dr["pid"] = this.queryProduct.id;
                    dr["uuid"] = uuid;
                    dr["handleId"] = "";
                    dr["nodeType"] = "3";
                    dr["nodeType_dictText"] = "物料";
                    dtBand.Rows.Add(dr);
                    this.dataGridView1.FirstDisplayedScrollingRowIndex = this.dataGridView1.Rows.Count - 1;
                }
            }));
            queryForm.initAddMaterialButton(GValues.CADCreateMaterialCode);
            queryForm.Owner = this;
            Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(this, queryForm);
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            getBomItem();
        }
        #region 行拖动示例
        //本身窗行的口的拖动，  先做这个
        private Rectangle dragBoxFromMouseDown;
        private int rowIndexFromMouseDown;
        private int rowIndexOfItemUnderMouseToDrop;
        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            //获取鼠标按下时行的索引值
            rowIndexFromMouseDown = dataGridView1.HitTest(e.X, e.Y).RowIndex;

            if (rowIndexFromMouseDown != -1)
            {
                //记录按下鼠标的点
                //DragSize指示在开始拖动操作前鼠标可以移动的范围
                Size dragSize = SystemInformation.DragSize;

                //用DragSize创建一个以鼠标为中心的矩形
                dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
            }
            else
            {
                //如果鼠标不在datagridview上，重置矩形
                dragBoxFromMouseDown = Rectangle.Empty;
            }
        }

        private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
        {
            if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
            {
                //如果鼠标移动到矩形框外面，开始拖拽
                if (dragBoxFromMouseDown != Rectangle.Empty && !dragBoxFromMouseDown.Contains(e.X, e.Y))
                {
                    if (this.dataGridView1.CurrentCell.ColumnIndex != 2) //按第二列不做操作
                    {
                        //执行tt拖拽，传入数据
                        DragDropEffects dropEffect = dataGridView1.DoDragDrop(dataGridView1.Rows[rowIndexFromMouseDown], DragDropEffects.Move);
                    }
                }
            }
        }

        private void dataGridView1_DragDrop(object sender, DragEventArgs e)
        {
            //由于鼠标的位置是与屏幕相关的，它必须转换为与客户端相匹配的点
            Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));

            //获取鼠标按下时的行的索引值
            rowIndexOfItemUnderMouseToDrop = dataGridView1.HitTest(clientPoint.X, clientPoint.Y).RowIndex;
            if (rowIndexOfItemUnderMouseToDrop > 0)
            {
                //如果拖放的行为为从将某一行移动然后移除，插入到某一行
                if (e.Effect == DragDropEffects.Move)
                {
                    DataGridViewRow rowToMove = e.Data.GetData(typeof(DataGridViewRow)) as DataGridViewRow;
                    DataRow dr = ((rowToMove).DataBoundItem as DataRowView).Row;
                    DataRow drr = dtBand.NewRow();
                    drr.ItemArray = dr.ItemArray;
                    dtBand.Rows.RemoveAt(rowIndexFromMouseDown);
                    dtBand.Rows.InsertAt(drr, rowIndexOfItemUnderMouseToDrop);
                }
            }

        }

        private void dataGridView1_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }
     #endregion
        #region 编辑BOM
        public void BaigeBlockGetMainProductCode(Action<String> callback)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            BasProductImport importProduct = new BasProductImport();
            string baigeProductCode = "";
            string materialHeigh = "";
            string materialSpec = "";
            string materialFace = "";
            string dwgPath = Path.GetDirectoryName(doc.Name);
            importProduct.customerCode = "C001";
            importProduct.unitName = "PCS";
            importProduct.productVer = "A";
            importProduct.productTypeName = "半成品";
            importProduct.currencyName = "人民币";

            // 选择块
            PromptEntityOptions blockOptions = new PromptEntityOptions("\n请选择一个块: ");
            blockOptions.SetRejectMessage("\n选择的对象不是块。");
            blockOptions.AddAllowedClass(typeof(BlockReference), true);

            PromptEntityResult blockResult = ed.GetEntity(blockOptions);
            if (blockResult.Status != PromptStatus.OK)
                return;

            ObjectId blockId = blockResult.ObjectId;

            // 获取块的定义
            using (Transaction trans = doc.TransactionManager.StartTransaction())
            {
                BlockReference blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead);
                if (blockRef != null)
                {
                    string blockName = blockRef.Name;
                    importProduct.cadHandleId = blockRef.Handle.Value.ToString();
                    baigeBlockCadHandleId = blockRef.Handle.Value.ToString();
                    // 输出块引用的信息
                    ed.WriteMessage("\n找到块引用: {0}", blockName);

                    // 遍历块引用中的所有属性
                    foreach (ObjectId attId in blockRef.AttributeCollection)
                    {
                        AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead);
                        if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                        {
                            importProduct.code = attRef.TextString;
                            importProduct.custCode = attRef.TextString;
                            importProduct.localAttachment = dwgPath + "/" + attRef.TextString + ".dwg";
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductName) //"零件名称"
                        {
                            importProduct.name = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_ProductName) //"产品名称"
                        {
                            importProduct.mainName = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_CaiLiao) //"材料"
                        {
                            materialSpec = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_CaiHou || attRef.Tag == GValues.BlockField_HouDu) //"材厚" "厚度"
                        {
                            materialHeigh = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SurfaceChuli) //"表面处理"
                        { 
                            materialFace = attRef.TextString;
                        }
                        ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                    }
                }

                trans.Commit();
            }
            //ed.WriteMessage("\n块内容已导出到 {newDwgPath}");
            if (importProduct.code == null || importProduct.code == "")
            {
                ed.WriteMessage("\n块内容没定义图号！");
            }
            else
            {
                //importProduct.description = materialSpec + "/" + materialHeigh + "/" + materialFace;
                importProduct.mainCompDesc = materialSpec;
                importProduct.faceProcess = materialFace;
                importProduct.materialThickness = materialHeigh;
                //MessageBox.Show("1:" + importProduct.code);
                BaigeGetProduct(importProduct.code, new Action<BasProduct>(product =>
                {
                    //MessageBox.Show("ok" );
                    if (product != null)
                    {
                        if (product.name == importProduct.mainName && product.name == importProduct.name)
                        {
                            BaigeUpdateProduct(importProduct, new Action<string>(r =>
                            {
                                //ed.WriteMessage("\n产品主料号系统获取成功！");
                                GValues.productCode = product.code;
                                callback.Invoke(product.code);
                            }));
                        }
                        else
                        {
                            //ed.WriteMessage("\n获取的产品不是主料号！");
                            callback.Invoke(null);
                        }
                    }
                    else
                    {
                        //List<BasProductImport> importProductList = new List<BasProductImport>();
                        //importProductList.Add(importProduct);
                        //BaigeSaveProduct(importProductList, new Action<string>((result) =>
                        //{
                        //    if (result != null && result == "ok")
                        //    {
                        //        GValues.productCode = importProduct.code;
                        //        ed.WriteMessage("\n产品料号系统创建成功！");
                        //        callback.Invoke(importProduct.code);
                        //    }
                        //    else
                        //    {
                        //        ed.WriteMessage("\n产品料号没创建成功！");
                        //    }
                        //}));
                        //ed.WriteMessage("\n系统没有获取到主料号！");
                        callback.Invoke(null);
                    }
                }));
            }
        }

        public void updateCadProductCode(List<BasProduct> productList, string handelId, Action<String> callback)
        {
            // 获取当前文档和数据库
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            BasProduct basProduct = productList[0];
            // 启动事务
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 打开图层表
                LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);

                // 遍历所有图层
                foreach (ObjectId layerId in lt)
                {
                    // 打开图层表记录
                    LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(layerId, OpenMode.ForRead);

                    // 检查图层是否锁定
                    if (ltr.IsLocked)
                    {
                        // 解锁图层
                        ltr.UpgradeOpen();
                        ltr.IsLocked = false;
                        ltr.DowngradeOpen();
                    }
                }

                string handle = handelId;
                if (handle != null)
                {
                    ObjectId objId = db.GetObjectId(false, new Handle(long.Parse(handle)), 0);

                    if (!objId.IsNull)
                    {
                        Entity entity = (Entity)tr.GetObject(objId, OpenMode.ForWrite);
                        if (entity is BlockReference)
                        {
                            BlockReference blockRef = entity as BlockReference;
                            // 获取块引用所在的图层
                            string layerName = blockRef.Layer;
                            // 获取块的名称
                            string blockName = blockRef.Name;
                            // 输出块引用的信息
                            ed.WriteMessage("\n在图层 {0} 找到块引用: {1}", layerName, blockName);
                            Dictionary<string, Dictionary<string, string>> productProcessResult = new Dictionary<string, Dictionary<string, string>>();
                            Dictionary<String, String> result = new Dictionary<string, string>();
                            // 遍历块引用中的所有属性
                            foreach (ObjectId attId in blockRef.AttributeCollection)
                            {
                                AttributeReference attRef = (AttributeReference)tr.GetObject(attId, OpenMode.ForWrite);

                                if (attRef.Tag == GValues.BlockField_SemiProductCode) //"零件编号"
                                {
                                    if (basProduct.code != null)
                                    {
                                        attRef.TextString = basProduct.code;
                                    }

                                }
                                ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                            }

                        }
                    }
                    else
                    {
                        ed.WriteMessage("\n未找到与指定 Handle ID 对应的对象。");
                    }
                }
                                
                // 提交事务
                tr.Commit();
                docLock.Dispose();
                doc.Editor.UpdateScreen();
                doc.Editor.Regen();
            }
            callback.Invoke("ok");
        }

        public void BaigeBlockGetProductCode(Action<String> callback)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            BasProductImport importProduct = new BasProductImport();
            GValues.CADMainProductCode = "";
            //GValues.customerDefCode = "C001";
            GValues.selectedBlockHandelId = "";
            //string mainProductName = "";
            //string baigeProductCode = "";
            //string materialHeigh = "";
            //string materialSpec = "";
            //string materialFace = "";
            bool isProductBom = false;
            string productCode = "";
            string dwgPath = Path.GetDirectoryName(doc.Name);
            //importProduct.customerCode = "C001";
            importProduct.unitName = "PCS";
            //importProduct.productVer = "A";
            importProduct.productTypeName = "半成品";
            importProduct.currencyName = "人民币";

            // 选择块
            PromptEntityOptions blockOptions = new PromptEntityOptions("\n请选择一个块: ");
            blockOptions.SetRejectMessage("\n选择的对象不是块。");
            blockOptions.AddAllowedClass(typeof(BlockReference), true);

            PromptEntityResult blockResult = ed.GetEntity(blockOptions);
            if (blockResult.Status != PromptStatus.OK)
                return;

            ObjectId blockId = blockResult.ObjectId;

            // 获取块的定义
            using (Transaction trans = doc.TransactionManager.StartTransaction())
            {
                BlockReference blockRef = (BlockReference)trans.GetObject(blockId, OpenMode.ForRead);
                if (blockRef != null)
                {
                    string blockName = blockRef.Name;
                    importProduct.cadHandleId = blockRef.Handle.Value.ToString();
                    baigeBlockCadHandleId = blockRef.Handle.Value.ToString();
                    GValues.selectedBlockHandelId = blockRef.Handle.Value.ToString();
                    // 输出块引用的信息
                    ed.WriteMessage("\n找到块引用: {0}", blockName);

                    //1**************
                        ResultBuffer rbXdata = blockRef.XData;

                        if (rbXdata != null)
                        {

                            // 遍历ResultBuffer以查看数据
                            foreach (TypedValue tv in rbXdata)
                            {
                                switch ((DxfCode)tv.TypeCode)
                                {
                                    case DxfCode.ExtendedDataRegAppName:
                                        //domainid = tv.Value.ToString();
                                        break;
                                    case DxfCode.ExtendedDataAsciiString:
                                        String data = tv.Value.ToString();
                                        if (data.IndexOf("productCode:") != -1)
                                        {
                                            productCode = data.Split(':')[1];
                                        }
                                        if (data.IndexOf("tableType:productBom") != -1)
                                        {
                                            isProductBom = true;
                                        }
                                        break;
                                    // 其他类型的DXF组码...
                                }
                            }
                        }
                    //1**************


                    //****
                     // 获取块定义
                    BlockTableRecord btr = trans.GetObject(blockRef.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;
            
                    // 遍历块内实体
                    foreach (ObjectId entId in btr)
                    {
                        Entity ent = trans.GetObject(entId, OpenMode.ForRead) as Entity;
                
                         // 修正为检测真正的 Table 对象
                            if (ent is Table) 
                            {
                                Table table = ent as Table;
                                ResultBuffer xdata = table.XData;
        
                                if (xdata != null)
                                {
                                    ResultBuffer rb = table.XData; // 获取实体的扩展数据

                                    // 遍历ResultBuffer以查看数据
                                    foreach (TypedValue tv in rb)
                                    {
                                        switch ((DxfCode)tv.TypeCode)
                                        {
                                            case DxfCode.ExtendedDataRegAppName:
                                                //domainid = tv.Value.ToString();
                                                break;
                                            case DxfCode.ExtendedDataAsciiString:
                                                String data = tv.Value.ToString();
                                                if (data.IndexOf("productCode:") != -1)
                                                {
                                                    productCode = data.Split(':')[1];
                                                }
                                                if (data.IndexOf("tableType:productBom") != -1)
                                                {
                                                    isProductBom = true;
                                                }
                                                break;
                                            // 其他类型的DXF组码...
                                        }
                                    }
                                }
                            }
                    }
                    //if (productCode != "" && isProductBom)
                    //{
                    //    ed.WriteMessage("\n块里已经定义了BOM表，请用TTE2命令修改！");
                    //    return;
                    //}

                    //****

                    // 遍历块引用中的所有属性
                    foreach (ObjectId attId in blockRef.AttributeCollection)
                    {
                        AttributeReference attRef = (AttributeReference)trans.GetObject(attId, OpenMode.ForRead);


                        if (attRef.Tag == GValues.BlockField_SemiProductCode) //"零件编码"
                        {
                            String tempCode = "";
                            tempCode = attRef.TextString;
                            tempCode = tempCode.Trim();
                            importProduct.code = tempCode;
                            importProduct.localAttachment = dwgPath + "/" + tempCode + ".dwg";
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductName) //"零件名称"
                        {
                            importProduct.name = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_CustomerCode) //"客户"
                        {
                            importProduct.customerCode = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductDrawingNo) //"零件图号"
                        {
                            importProduct.drawingNo = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductModel) //"零件规格"
                        {
                            importProduct.model = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductDescription) //"零件描述"
                        {
                            importProduct.description = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductCustCode) //"零件客户料号"
                        {
                            importProduct.custCode = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductVer) //"零件版本"
                        {
                            importProduct.productVer = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductSizeLength) //"零件长度"
                        {
                            importProduct.sizeLength = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductSizeWidth) //"零件宽度"
                        {
                            importProduct.sizeWidth = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductWeight) //"零件重量"
                        {
                            importProduct.weight = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductSurfaceChuli) //"零件喷涂"
                        {
                            importProduct.faceProcess = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductCaiLiao) //"零件材料"
                        {
                            importProduct.mainCompDesc = attRef.TextString;
                        }
                        if (attRef.Tag == GValues.BlockField_SemiProductCaiHou) //"零件材料厚度"
                        {
                            importProduct.materialThickness = attRef.TextString;
                        }

                        //if (attRef.Tag == GValues.BlockField_SemiProductCode) //"图号"
                        //{
                        //    importProduct.code = attRef.TextString;
                        //    //importProduct.custCode = attRef.TextString;
                        //    importProduct.localAttachment = dwgPath + "/" + attRef.TextString + ".dwg";
                        //}
                        //if (attRef.Tag == GValues.BlockField_SemiProductName)  //"零件名称"
                        //{
                        //    importProduct.name = attRef.TextString;
                        //}
                        //if (attRef.Tag == GValues.BlockField_ProductName) // "产品名称"
                        //{
                        //    mainProductName = attRef.TextString;
                        //}
                        //if (attRef.Tag == GValues.BlockField_CaiLiao) //"材料"
                        //{
                        //    materialSpec = attRef.TextString;
                        //}
                        //if (attRef.Tag ==  GValues.BlockField_CaiHou || attRef.Tag == GValues.BlockField_HouDu) //"材厚" "厚度"
                        //{
                        //    materialHeigh = attRef.TextString;
                        //}
                        //if (attRef.Tag == GValues.BlockField_SurfaceChuli ) //"表面处理"
                        //{
                        //    materialFace = attRef.TextString;
                        //}
                        ed.WriteMessage("\n  属性标签: {0}, 属性值: {1}", attRef.Tag, attRef.TextString);
                    }
                }

                trans.Commit();
            }
            //ed.WriteMessage("\n块内容已导出到 {newDwgPath}");
            if ((importProduct.code == null || importProduct.code == ""))
            {
                ed.WriteMessage("\n块内容没定义图号！");
            }
            else
            {
                //importProduct.description = materialSpec + "/" + materialHeigh + "/" + materialFace;
                //importProduct.mainCompDesc = materialSpec;
                //importProduct.faceProcess = materialFace;
                //importProduct.materialThickness = materialHeigh;
                //MessageBox.Show("1:" + importProduct.code);
                //string semiProductCode = importProduct.code;
                //if (GValues.AutoCreateSemiProductCode && (importProduct.code == null || importProduct.code == ""))
                //{
                //    semiProductCode = "共享发大财";
                //}
                BaigeGetProduct(importProduct.code, new Action<BasProduct>(product =>
                {
                    //SemiProductForm semiProductForm = new SemiProductForm(new Action<string>(check =>
                    //{
                    //    //MessageBox.Show(check);
                    //    if (check == "save")
                    //    {
                    //        List<BasProductImport> importProductList = new List<BasProductImport>();
                    //        importProductList.Add(importProduct);
                    //        BaigeSaveProduct(importProductList, new Action<string>((result) =>
                    //        {
                    //            if (result != null && result == "ok")
                    //            {
                    //                BasProduct basProduct = GValues.createSemiProductCodeList[0];
                    //                GValues.productCode = basProduct.code;
                    //                //ed.WriteMessage("\n产品料号系统创建成功！");
                    //                MessageBox.Show("产品料号系统不存在，系统创建成功！");
                    //                //LogHelper.WriteLog(tag + "产品料号系统创建成功！");
                    //                updateCadProductCode(GValues.createSemiProductCodeList, baigeBlockCadHandleId, new Action<string>(r => { }));
                    //                callback.Invoke(basProduct.code);
                    //            }
                    //            else
                    //            {
                    //                MessageBox.Show("产品没有创建成功！");
                    //                //ed.WriteMessage("\n产品料号没创建成功！");
                    //                //LogHelper.WriteLog(tag + "产品料号没创建成功！");
                    //            }
                    //        }));
                    //    }
                    //    if (check == "edit")
                    //    {
                    //        BaigeUpdateProduct(importProduct, new Action<string>(r =>
                    //        {
                    //            //ed.WriteMessage("\n产品料号系统获取成功！");
                    //            MessageBox.Show("产品料号系统已经存在，获取成功！");
                    //            //LogHelper.WriteLog(tag + "产品料号系统获取成功！");
                    //            GValues.productCode = product.code;
                    //            callback.Invoke(product.code);
                    //        }));
                    //    }
                    //    if (check == "cancel")
                    //    {
                    //        GValues.productCode = product.code;
                    //        callback.Invoke(product.code);
                    //    }
                    //}));
                    //List<string> checkResults = new List<string>();
                    if (product == null)
                    {
                        MessageBox.Show("系统没有查找到产品数据！");
                        //semiProductForm.InitFormFields(importProduct, "save", checkResults);
                        //Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, semiProductForm);
                    }
                    else
                    {
                        GValues.productCode = product.code;
                        callback.Invoke(product.code);

                        //CheckUpdateFields(importProduct, product, checkResults);
                        //if (checkResults.Count > 0)
                        //{
                        //    semiProductForm.InitFormFields(importProduct, "edit", checkResults);
                        //    Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(null, semiProductForm);
                        //}
                        //else
                        //{
                        //    semiProductForm.Close();
                        //    semiProductForm.Dispose();
                        //    semiProductForm = null;
                        //    GValues.productCode = product.code;
                        //    callback.Invoke(product.code);
                        //}
                    }

                    //MessageBox.Show("ok" );
                    //if (product != null)
                    //{
                    //    BaigeUpdateProduct(importProduct, new Action<string>(r =>
                    //    {
                    //        //ed.WriteMessage("\n产品料号系统获取成功！");
                    //        GValues.productCode = product.code;
                    //        if (importProduct.name == mainProductName && importProduct.name == product.name)
                    //        {
                    //            GValues.CADMainProductCode = product.code;
                    //            GValues.customerDefCode = product.customerDefCode;
                    //        }
                    //        callback.Invoke(product.code);
                    //    }));
                    //}
                    //else
                    //{
                    //    List<BasProductImport> importProductList = new List<BasProductImport>();
                    //    if (GValues.customerDefCode != null && GValues.customerDefCode != "")
                    //    {
                    //        importProduct.customerCode = GValues.customerDefCode;
                    //    }
                    //    else
                    //    {
                    //        importProduct.customerCode = "C001";
                    //    }
                        
                    //    importProductList.Add(importProduct);
                    //    BaigeSaveProduct(importProductList, new Action<string>((result) =>
                    //    {
                    //        if (result != null && result == "ok")
                    //        {
                    //            GValues.productCode = importProduct.code;
                    //            //ed.WriteMessage("\n产品料号系统创建成功！");
                    //            callback.Invoke(importProduct.code);
                    //        }
                    //        else
                    //        {
                    //            //ed.WriteMessage("\n产品料号没创建成功！");
                    //        }
                    //    }));
                    //}
                }));
            }
        }

        private void CheckUpdateFields(BasProductImport productImport, BasProduct product, List<string> checkResults)
        {
            if (productImport.name != product.name)
            {
                checkResults.Add("零件名称：" + product.name + "/" + productImport.name);
            }
            if (productImport.custCode != product.custCode)
            {
                checkResults.Add("客户料号：" + product.custCode + "/" + productImport.custCode);
            }
            if (productImport.drawingNo != product.drawingNo)
            {
                checkResults.Add("零件图号：" + product.drawingNo + "/" + productImport.drawingNo);
            }
            if (productImport.model != product.model)
            {
                checkResults.Add("零件规格：" + product.model + "/" + productImport.model);
            }
            if (productImport.productVer != product.productVer)
            {
                checkResults.Add("零件版本：" + product.productVer + "/" + productImport.productVer);
            }
            if (productImport.description != product.description)
            {
                checkResults.Add("零件描述：" + product.description + "/" + productImport.description);
            }
            if (productImport.mainCompDesc != product.mainCompDesc)
            {
                checkResults.Add("零件材料：" + product.mainCompDesc + "/" + productImport.mainCompDesc);
            }
            if (productImport.faceProcess != product.faceProcess)
            {
                checkResults.Add("表面处理：" + product.faceProcess + "/" + productImport.faceProcess);
            }
            if (productImport.materialThickness != product.materialThickness)
            {
                checkResults.Add("材料厚度：" + product.materialThickness + "/" + productImport.materialThickness);
            }
            if (productImport.sizeLength != product.sizeLength)
            {
                checkResults.Add("长度：" + product.sizeLength + "/" + productImport.sizeLength);
            }
            if (productImport.sizeWidth != product.sizeWidth)
            {
                checkResults.Add("宽度：" + product.sizeWidth + "/" + productImport.sizeWidth);
            }
            if (productImport.weight != product.weight)
            {
                checkResults.Add("重量：" + product.weight + "/" + productImport.weight);
            }
        }  
        public void BaigeUpdateProduct(BasProductImport basProduct, Action<string> callback)
        {
            String tag = "updateProduct";
            string postData = JsonConvert.SerializeObject(basProduct);
            Http.CreateHttpClient(GValues.domainLink + "/bas/basProduct/cad-edit-local", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
            {
                var responCode = Convert.ToInt32(r.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResult<Object> cc = JsonConvert.DeserializeObject<ResponResult<Object>>(r.AckStr());
                    if (cc.success)
                    {
                        callback.Invoke("ok");
                        LogHelper.WriteLog(tag + "保存产品数据成功！");
                    }
                    else
                    {
                        MessageBox.Show(cc.message);
                        callback.Invoke(null);
                        LogHelper.WriteLog(tag + "接口访问错误: " + cc.message);
                    }


                }
                else
                {
                    LogHelper.WriteLog(tag + "保存产品数据失败！" + r.Code + " " + " " + responCode + " " + r.Error);

                }
            }));
        }
        public void BaigeSaveProduct(List<BasProductImport> importProductList, Action<string> callback)
        {
            String tag = "saveProductList";
            GValues.createSemiProductCodeList = new List<BasProduct>();
            string postData = JsonConvert.SerializeObject(importProductList);
            Http.CreateHttpClient(GValues.domainLink + "/bas/basProduct/importByExcel", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
            {
                var responCode = Convert.ToInt32(r.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResult<Object> cc1 = JsonConvert.DeserializeObject<ResponResult<Object>>(r.AckStr());
                    ResponResult<BindingList<BasProduct>> cc = JsonConvert.DeserializeObject<ResponResult<BindingList<BasProduct>>>(r.AckStr());
                    if (cc.success && cc.message.IndexOf("导入成功数据:1") != -1)
                    {
                        BindingList<BasProduct> items = cc.result;
                        List<BasProduct> list = items.ToList();
                        GValues.createSemiProductCodeList = list;
                        callback.Invoke("ok");
                        LogHelper.WriteLog(tag + "保存产品数据成功！");
                    }
                    else
                    {
                        MessageBox.Show(cc1.message);
                        callback.Invoke(null);
                        LogHelper.WriteLog(tag + "接口访问错误: " + cc.message);
                    }


                }
                else
                {
                    LogHelper.WriteLog(tag + "保存产品数据失败！" + r.Code + " " + " " + responCode + " " + r.Error);

                }
            }));
        }
        public void BaigeGetProduct(String productCode, Action<BasProduct> callback)
        {
            //MessageBox.Show(productCode);
            string code = productCode;
            QueryParamater param = new QueryParamater();
            param.superQueryMatchType = "and";
            List<ParamArr> superArrs = new List<ParamArr>();
            ParamArr paramArr = new ParamArr();
            paramArr.rule = "eq";
            paramArr.type = "string";
            paramArr.val = code;
            paramArr.field = "p.code";
            superArrs.Add(paramArr);
            param.superQueryParams = System.Net.WebUtility.UrlDecode(JsonConvert.SerializeObject(superArrs));
            LogHelper.WriteLog("开始查询产品！" + GValues.tenant + " token :" + GValues.token);
            //MessageBox.Show("tenant :" + GValues.tenant + " token :" + GValues.token + " productcode : " + productCode + " domainLink: " + GValues.domainLink);
            String tag = "getProductData";
            Http.CreateHttpClient(GValues.tenant, GValues.token).GetAsync(GValues.domainLink + "bas/basProduct/list?superQueryParams=" + param.superQueryParams + "&superQueryMatchType=" + param.superQueryMatchType, new Action<Http.HttpResp>((r11) =>
            {
                //MessageBox.Show(" r :" + r11.Code);
                int responCode = 0;
                try
                {
                    responCode = Convert.ToInt32(r11.Code);
                }
                catch (System.Exception ex)
                {

                }

                if (r11.Code == HttpStatusCode.OK || responCode == 200) //访问成功
                {
                    ResponResultA<BasProduct> cc = JsonConvert.DeserializeObject<ResponResultA<BasProduct>>(r11.AckStr());
                    if (cc.success)
                    {
                        //MessageBox.Show(" message : " + cc.message);
                        BindingList<BasProduct> products = cc.result.records;
                        BasProduct product = new BasProduct();
                        //MessageBox.Show(" products :" + products.Count);
                        if (products != null && products.Count() == 1)
                        {
                            product = products[0];
                            //MessageBox.Show("product: " + product.code);
                            if (product.code != null && productCode == product.code.Trim())
                            {
                                //MessageBox.Show("exit....");
                                callback.Invoke(product);
                            }
                            else
                            {
                                LogHelper.WriteLog(tag + "没找到产品数据！");
                            }
                        }
                        else
                        {
                            callback.Invoke(null);
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog(tag + "接口访问错误: " + cc.message);
                    }
                }
                else
                {
                    LogHelper.WriteLog(tag + "网络连接错误: " + r11.Error);
                }
            }));
        }

        public  void SetLayer0XData()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            DocumentLock docLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument();
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 获取图层表
                LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;

                // 确保0图层存在
                if (!lt.Has("0"))
                {
                    lt.UpgradeOpen();
                    LayerTableRecord ltr = new LayerTableRecord();
                    ltr.Name = "0";
                    lt.Add(ltr);
                    tr.AddNewlyCreatedDBObject(ltr, true);
                }

                // 打开0图层记录
                LayerTableRecord layer0 = tr.GetObject(lt["0"], OpenMode.ForWrite) as LayerTableRecord;

                // 注册应用程序名（必须先在数据库中注册）
                //RegAppTable rat = tr.GetObject(db.RegAppTableId, OpenMode.ForRead) as RegAppTable;
                //if (!rat.Has("ACAD"))
                //{
                //    rat.UpgradeOpen();
                //    RegAppTableRecord ratr = new RegAppTableRecord();
                //    ratr.Name = "ACAD";
                //    rat.Add(ratr);
                //    tr.AddNewlyCreatedDBObject(ratr, true);
                //}

                // 创建扩展数据
                ResultBuffer rb = new ResultBuffer(
                    new TypedValue(1001, "ACAD"),         // 应用程序名
                    new TypedValue(1000, "mainProductCode:" + GValues.CADMainProductCode),       // 字符串类型
                    new TypedValue(1000, "customerDefCode:" + GValues.customerDefCode),
                    new TypedValue(1070, 2025),            // 整型数据
                    new TypedValue(1040, 3.1415)           // 浮点型数据
                );

                // 附加扩展数据到图层
                layer0.XData = rb;
                rb.Dispose();
                docLock.Dispose();

                tr.Commit();
            }
        }
        public void ReadLayer0XData()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;


            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                // 获取0图层记录
                LayerTable lt = tr.GetObject(db.LayerTableId, OpenMode.ForRead) as LayerTable;
                LayerTableRecord layer0 = tr.GetObject(lt["0"], OpenMode.ForRead) as LayerTableRecord;

                // 获取指定应用的扩展数据
                ResultBuffer rb = layer0.GetXDataForApplication("ACAD");

                if (rb == null)
                {
                    doc.Editor.WriteMessage("\n未找到ACAD的扩展数据");
                    return;
                }

                // 解析扩展数据
                doc.Editor.WriteMessage("\n扩展数据内容：");
                foreach (TypedValue tv in rb)
                {
                    doc.Editor.WriteMessage("\n类型码:" + tv.TypeCode + " 值:" + tv.Value);
                    switch ((DxfCode)tv.TypeCode)
                    {
                        case DxfCode.ExtendedDataRegAppName:
                            //rb.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, tv.ToString()));
                            break;
                        case DxfCode.ExtendedDataAsciiString:
                            if (tv.ToString().IndexOf("mainProductCode:") != -1)
                            {
                                GValues.CADMainProductCode = tv.Value.ToString().Split(':')[1];
                            }
                            if (tv.ToString().IndexOf("customerDefCode:") != -1)
                            {
                                GValues.customerDefCode = tv.Value.ToString().Split(':')[1];
                            }
                            break;
                        // 其他类型的DXF组码...
                    }

                }

                rb.Dispose();
                tr.Commit();
            }
        }


        #endregion

        private void textBox1_TextChanged(object sender, System.EventArgs e)
        {

        }

        private void textBox11_TextChanged(object sender, System.EventArgs e)
        {

        }

        private void button8_Click(object sender, System.EventArgs e)
        {
            getBomItem();
        }
    }
}
